package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.GroupUserSortAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.utils.GroupNameUtil;
import com.efounder.chat.utils.GroupUsersDialogHelper;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.HanyuParser;
import com.efounder.mobilecomps.contacts.PinyinComparator;
import com.efounder.mobilecomps.contacts.SideBar;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.thirdpartycomps.stickylistheaders.StickyListHeadersListView;
import com.efounder.utils.ResStringUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 选择群组中的单个联系人
 * 需要传入id，类型为int。title为标题，可不传
 *
 * @author slp
 * @date 2018/3/21
 */
public class SelectGroupUserActivity extends BaseActivity implements
        AdapterView.OnItemClickListener,
        StickyListHeadersListView.OnHeaderClickListener,
        StickyListHeadersListView.OnStickyHeaderOffsetChangedListener,
        StickyListHeadersListView.OnStickyHeaderChangedListener {

    public static final int SUCCESS = 1;
    private static final int FAILER = -1;

    private StickyListHeadersListView stickyList;
    private SideBar sideBar;
    private TextView dialog;
    private GroupUserSortAdapter adapter;
    private boolean fadeHeader = true;
    private int groupId;//群号
    private int queryFrom;//从单纯从Groups查询是0，其他是1；
    private int createId;//群组创建者id
    private Group group;
    private TextView tv_m_total;//显示群成员人数
    private GroupUsersDialogHelper helper;
    private boolean isCreateor = false;//当前登录用户是否是创建者
    private int appUserId;//当前登录的用户
    private User appLoginUser;
    //是否显示自己
    private boolean isShowSelf = true;

    /**
     * 汉字转换成拼音的类
     */
    private List<User> sourceDataList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private AsyncTask<Void, Void, String> asyncTask;

    private String titleStr;
    private TextView tvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_group_user);

        groupId = getIntent().getIntExtra("id", 1);
        titleStr = getIntent().getStringExtra("title");
        queryFrom = getIntent().getIntExtra("queryFrom", 1);
        isShowSelf = getIntent().getBooleanExtra("isShowSelf", true);

        appUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));

        initViews();
        loadData();
    }

    private void initViews() {


        // 实例化汉字转拼音类

        tvTitle = (TextView) findViewById(R.id.tv_title);
        if (titleStr != null) {
            tvTitle.setText(titleStr);
        }

        pinyinComparator = new PinyinComparator();
        tv_m_total = (TextView) findViewById(R.id.tv_m_total);
        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        appLoginUser = new User();

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    stickyList.setSelection(position);
                }

            }
        });

        stickyList = (StickyListHeadersListView)
                findViewById(R.id.country_lvcountry);
        stickyList.setOnItemClickListener(this);
//        stickyList.setOnItemLongClickListener(this);
        stickyList.setOnHeaderClickListener(this);
        stickyList.setOnStickyHeaderChangedListener(this);
        stickyList.setOnStickyHeaderOffsetChangedListener(this);
        stickyList.setDrawingListUnderStickyHeader(true);
        stickyList.setAreHeadersSticky(true);
        stickyList.setStickyHeaderTopOffset(-10);
        stickyList.setFastScrollEnabled(true);
        stickyList.setFastScrollAlwaysVisible(true);
        sourceDataList = new ArrayList<User>();
    }

    //加载数据
    private void loadData() {
        sourceDataList.clear();

        if (queryFrom == 1) {
            group = WeChatDBManager.getInstance().getGroupWithUsers(groupId);
        } else {
            group = WeChatDBManager.getInstance().getGroupWithUsersInGroups(groupId);
        }
        createId = group.getCreateId();
        if (createId == appUserId) {
            isCreateor = true;
        }

        List<User> myList = group.getUsers();
        tv_m_total.setText("(" + String.valueOf(myList.size()) + ")");

        // 根据a-z进行排序源数据

        sortByAsync(myList);
//        Collections.sort(sourceDataList, pinyinComparator);
//
//
//        adapter = new GroupUserSortAdapter(getActivity(), sourceDataList, group);
//        stickyList.setAdapter(adapter);
//        adapter.notifyDataSetChanged();


    }

    /**
     * 为ListView填充数据
     *
     * @param users
     * @return
     */
    private List<User> filledData(List<User> users) {
        List<User> usersList = new ArrayList<User>();
        int mySelfId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID));
        // String[] idData = getResources().getStringArray(R.array.id);
        for (User user : users) {
            // 汉字转换成拼音
            String userName = "";
            // User friendUser = GroupNameUtil.getGroupUser(group.getGroupId(), user.getId(), WeChatDBManager.getInstance());
            if (!user.getNickName().equals(String.valueOf(user.getId()))) {
                userName = GroupNameUtil.getGroupUserName(user);
            } else {
                userName = user.getNickName();
            }
            user.setOtherGroupRemark(userName);
            if (user.getId() == appUserId) {
                appLoginUser = user;
            }
            String pinyin = new HanyuParser().getStringPinYin(userName);
            String sortString = pinyin.substring(0, 1).toUpperCase(
                    Locale.getDefault());

            if (user.getGroupUserType() == User.GROUPCREATOR || group.getCreateId() == user.getId()) {
                user.setSortLetters("↑");
            } else if (user.getGroupUserType() == User.GROUPMANAGER) {
                user.setSortLetters("☆");
            } else if (sortString.matches("[A-Z]")) {// 正则表达式，判断首字母是否是英文字母
                user.setSortLetters(sortString.toUpperCase(Locale.getDefault()));
            } else {
                user.setSortLetters("#");
            }

            if (!isShowSelf && user.getId() == mySelfId) {
                //不显示自己
                continue;
            }
            usersList.add(user);
        }

        return usersList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<User> filterDateList = new ArrayList<User>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDataList;
        } else {
            filterDateList.clear();
            for (User user : sourceDataList) {
                String name = user.getReMark();
                if (containString(name, filterStr)) {
                    filterDateList.add(user);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    private boolean containString(String name, String filterStr) {
        String namePinyin = new HanyuParser().getStringPinYin(name);
        for (int i = 0; i < filterStr.length(); i++) {
            String singleStr = filterStr.substring(i, i + 1);
            // 汉字
            if (name.contains(singleStr)) {
                if (i == filterStr.length() - 1) {
                    return true;
                }
                continue;
            }
            // 英文
            if (namePinyin.contains(singleStr)) {
                int currentIndex = namePinyin.indexOf(singleStr);
                namePinyin = namePinyin.substring(currentIndex + 1,
                        namePinyin.length());
            } else {// 不包含
                break;
            }
            if (i == filterStr.length() - 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        User user = (User) adapter.getItem(position);
        Intent intent = new Intent();
        intent.putExtra("selectUser", user);
        setResult(SUCCESS, intent);

        finish();
    }

    @Override
    public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId, boolean currentlySticky) {

    }

    @Override
    public void onStickyHeaderOffsetChanged(StickyListHeadersListView l, View header, int offset) {
        if (fadeHeader
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            header.setAlpha(1 - (offset / (float) header.getMeasuredHeight()));
        }
    }

    @Override
    public void onStickyHeaderChanged(StickyListHeadersListView l, View header, int itemPosition, long headerId) {
        header.setAlpha(1);
    }

    /**
     * 更新界面
     */
    public interface UpdateDataCallBack {
        public void updateDataNotication();
    }

    //排序
    @SuppressLint("StaticFieldLeak")
    private void sortByAsync(final List<User> myList) {
        asyncTask = new AsyncTask<Void, Void, String>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                showLoading(ResStringUtil.getString(R.string.common_text_loading));
            }

            @Override
            protected String doInBackground(Void... params) {
                sourceDataList.addAll(filledData(myList));
                Collections.sort(sourceDataList, pinyinComparator);
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                dismissLoading();
                int posotion = stickyList.getFirstVisiblePosition();
                adapter = new GroupUserSortAdapter(SelectGroupUserActivity.this, sourceDataList, group);
                stickyList.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                stickyList.setSelection(posotion);
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
                dismissLoading();
            }
        };
        asyncTask.executeOnExecutor(Executors.newCachedThreadPool());

    }
}
